package ch.bfh.parallaxis.helpers;

public class ParallaXisArray {
	private final double[] buffer;
	private int bufferSize = 400;
	private int virtualBufferSize = 400;
	private int actualBufferSize = 0;
	private int first;
	private int last;   
	private double average;
	private double sum;
	private double lastValue;
	
	public ParallaXisArray()
	{
		this.buffer = new double[this.bufferSize];
	}
	public ParallaXisArray(final int bufferSize)
	{
		this.bufferSize = bufferSize;
	    this.virtualBufferSize = this.bufferSize;
	    this.buffer = new double[this.bufferSize];
	}
	public void addValue(double value)
	{
		 this.lastValue = this.buffer[this.last];
			this.buffer[this.last] = value;
			this.sum += value;
			this.last = (this.last + 1) % this.virtualBufferSize;// this.buffer.length;
			if (this.first != this.last) {
				this.actualBufferSize++;
			} else {
				this.first = (this.last + 1) % this.virtualBufferSize;// this.buffer.length;
				this.sum -= this.lastValue;
			}
	}
	public void clear()
	{
		this.first = this.last;
	    this.actualBufferSize = 0;
	    this.sum = 0;
	    this.average = 0;
	}
	public synchronized double getAverage() {
		
	       if (this.actualBufferSize > 0) {
	           this.average = (double) ((double)this.sum / (double)this.actualBufferSize);
	           //System.out.println("Average: " + this.average + "/sum: "+ this.sum + "/Buffer: "+this.actualBufferSize);
	       }
	       return this.average;
	}
	
	public int getActualBufferSize() {
		return actualBufferSize;
	}
	public void setVirtualBufferSize(int value)
	{
		this.virtualBufferSize = value;
	}
	public int getVirtualBufferSize()
	{
		return this.virtualBufferSize;
	}
	public double calculateMedian()
	{
		java.util.Arrays.sort(buffer);
		if(buffer.length % 2 == 0)
		{
			//Gerade anzahl
			//-1 da der Index bei 0 beginnt
			int index = (buffer.length / 2)-1;
			double a = buffer[index];
			double b = buffer[index+1];
			return (a + b)/2;
		}
		else
		{
			//Ungerade Anzahl
			return buffer[buffer.length/2];
		}
	}

}
